package com.zjuh.qss.biz.similar;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import wint.tools.similar.content.Content;
import wint.tools.util.CloseableIterator;
import wint.tools.util.SqlUtil;

import com.zjuh.qss.biz.dao.TaobaoCatDAO;
import com.zjuh.qss.biz.dao.TaobaoItemDescriptionDAO;
import com.zjuh.qss.biz.domain.taobao.TaobaoCatDO;
import com.zjuh.qss.biz.domain.taobao.TaobaoItemDescriptionDO;

public class TaoItemSqlResultCloseableIterator implements CloseableIterator<Content> {

	private ResultSet rs;
	
	private Statement stmt;

	private Connection conn;
	
	private TaobaoCatDAO taobaoCatDAO;
	
	private TaobaoItemDescriptionDAO taobaoItemDescriptionDAO;
	
	public TaoItemSqlResultCloseableIterator(ResultSet rs, Statement stmt, Connection conn, 
			TaobaoCatDAO taobaoCatDAO, TaobaoItemDescriptionDAO taobaoItemDescriptionDAO) {
		super();
		this.rs = rs;
		this.stmt = stmt;
		this.conn = conn;
		this.taobaoCatDAO = taobaoCatDAO;
		this.taobaoItemDescriptionDAO = taobaoItemDescriptionDAO;
	}

	public void close() {
		SqlUtil.close(rs);
		SqlUtil.close(stmt);
		SqlUtil.close(conn);
	}

	public boolean hasNext() {
		try {
			return rs.next();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public Content next() {
		try {
			long itemId = rs.getLong("item_id");
			long cid = rs.getLong("cid");
			String itemTitle = rs.getString("item_title");
			TaobaoItemContent taobaoItemContent = new TaobaoItemContent();
			taobaoItemContent.setId(String.valueOf(itemId));
			taobaoItemContent.setItemTitle(itemTitle);
			
			TaobaoCatDO taoCatDO = taobaoCatDAO.queryByCid(cid);
			if (taoCatDO != null) {
				taobaoItemContent.setCatName(taoCatDO.getName());
			}
			
			TaobaoItemDescriptionDO taobaoItemDescriptionDO = taobaoItemDescriptionDAO.queryByItemId(itemId);
			if (taobaoItemDescriptionDO != null) {
				taobaoItemContent.setDescription(taobaoItemDescriptionDO.getContent());
			}
			
			return taobaoItemContent;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void remove() {
		throw new UnsupportedOperationException();
	}

}
